package net.itemzone.framework.webservice.cxf.server;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.cxf.binding.soap.SoapFault;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.jaxrs.ext.MessageContextImpl;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.log4j.Logger;

import sun.misc.BASE64Decoder;

/** 
 * <p>Title: </p> 
 * <p>Description: </p>
 * <p>Company: 深圳任子行网络技术有限公司</p> 
 * @version 1.00 Apr 13, 2009
 * @author ZhaoJunFei zhaoyuntao
 *  
 * Modified History: 
 *  
 */
public class HttpAuthentiacationInterceptor extends AbstractPhaseInterceptor<Message>{
	private static Logger log = Logger.getLogger(HttpAuthentiacationInterceptor.class);
	private HttpAuthenticationHandler httpAuthenticationHandler;
	private BASE64Decoder decoder=new BASE64Decoder();
	public HttpAuthentiacationInterceptor(){
		super(Phase.PRE_PROTOCOL);
	}
	public HttpAuthentiacationInterceptor(String phase) {
		super(phase);
	}
	public void handleMessage(Message message) throws Fault {
		MessageContextImpl context = new MessageContextImpl(message);
		HttpServletRequest request = context.getHttpServletRequest();
		String headerMessage = request.getHeader("authorization"); 
		if(headerMessage==null || headerMessage.equals("")){
			throw new SoapFault("请在http头里面添加用户名和密码的验证信息",Fault.FAULT_CODE_SERVER);
		}
		String ipAddress = request.getRemoteAddr();
        String username = null;
		String password = null;
		try {
			username = (new String(decoder.decodeBuffer(headerMessage
					.substring(6)))).split(":")[0];
			password = (new String(decoder.decodeBuffer(headerMessage
					.substring(6)))).split(":")[1];
		} catch (IOException e) {
			throw new SoapFault("获取header信息错误....",Fault.FAULT_CODE_SERVER);
		}
		log.debug("客户端IP"+ipAddress);
		log.debug("用户名:"+username);
		log.debug("密  码:"+password);
		try{
			httpAuthenticationHandler.authenticate(ipAddress, username,password);
		}catch(Exception e){
			throw new SoapFault("验证IP地址用户名密码失败",Fault.FAULT_CODE_SERVER);
		}
	}
	
	public void setHttpAuthenticationHandler(
			HttpAuthenticationHandler httpAuthenticationHandler) {
		this.httpAuthenticationHandler = httpAuthenticationHandler;
	}
	
}
